<template>
  <div class="app-container">  
        
    <el-row :gutter="20">
      <!--左侧列表-->
      <el-col :span="16" :xs="24">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['dev:form:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleCopy"
          v-hasPermi="['dev:form:add']"
        >复制</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="formList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="字段" align="center" prop="field" />
      <el-table-column label="标签" align="center" prop="label" />
      <el-table-column label="类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dev_form_type" :value="scope.row.type"/>
        </template>
      </el-table-column>
      <el-table-column label="必填" align="center" prop="required">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_yes_no" :value="scope.row.required"/>
        </template>
      </el-table-column>
      <el-table-column label="数据源" align="center" prop="ds" />
      <el-table-column label="模式" align="center" prop="mode">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.dev_form_mode" :value="scope.row.mode"/>
        </template>
      </el-table-column>
      <el-table-column label="默认值" align="center" prop="defaults" />
      <el-table-column label="排序" align="center" prop="sorts" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:form:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:form:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="pager.page"
      :limit.sync="pager.limit"
      @pagination="getList"
    />

      </el-col>
      <!--右侧预览-->
      <el-col :span="8" :xs="24">
          <el-card class="box-card">
        <div slot="header" class="clearfix">
            <span>效果预览</span>
        </div>
        <iframe id="preview" :src="'/app.html#/pages/dev/form?app='+appInfo.code" height="600" v-if="appInfo" style="border:scroll"></iframe>
        </el-card>
          
      </el-col>
    </el-row>

    <!-- 添加或修改表单字段对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="字段" prop="field">
          <el-input v-model="form.field" placeholder="请输入字段" />
        </el-form-item>
        <el-form-item label="标签" prop="label">
          <el-input v-model="form.label" placeholder="请输入标签" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="dict in dict.type.dev_form_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="必填" prop="required">
          <el-radio-group v-model="form.required">
            <el-radio
              v-for="dict in dict.type.sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数据源" prop="ds">
          <el-input v-model="form.ds" placeholder="请输入数据源" />
        </el-form-item>
        <el-form-item label="模式" prop="mode">
          <el-radio-group v-model="form.mode">
            <el-radio
              v-for="dict in dict.type.dev_form_mode"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="默认值" prop="defaults">
          <el-input v-model="form.defaults" placeholder="请输入默认值" />
        </el-form-item>
        <el-form-item label="排序" prop="sorts">
          <el-input v-model="form.sorts" placeholder="请输入排序" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 复制字段对话框 -->
    <el-dialog title="复制字段" :visible.sync="openCopy" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="copyForm" :model="copyForm" label-width="80px">
        <el-form-item label="应用" prop="app_id">
          <el-select v-model="copyForm.app_id" placeholder="请选择应用" @change="loadForms" filterable>
            <el-option
              v-for="m in appOptions"
              :key="m.id"
              :label="m.name"
              :value="m.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="表单字段" prop="required">
          <el-checkbox-group v-model="copyForm.form_ids">
            <el-checkbox
              v-for="m in formOptions"
              :key="m.id"
              :value="m.id"
              :label="m.id"
            >{{m.label}} {{m.field}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCopy">确 定</el-button>
        <el-button @click="cancelCopy">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { apiGet, apiPost, apiPut, apiDelete, apiDs, apiExport, apiDownload } from "@/api/openapi";

export default {
  name: "Form",
  dicts: ['dev_form_mode', 'dev_form_type', 'sys_yes_no'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单字段表格数据
      formList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      appId: null,
      // 查询参数
      queryParams: {
        app_id: null,
        type: null,
        field: null,
        label: null,
        required: null,
        ds: null,
        mode: null,
        defaults: null,
        sorts: null,
        "@alias": "t",
        "@exp": {
        }
      },
      pager: {
        page: 1,
        limit: 10,
        order: "sorts asc",
      },
      // 导入参数
      upload: false,
      // 表单参数
      form: {},
      appInfo: null,
      openCopy: false,
      copyForm:{},
      appOptions: [],
      formOptions: [],
      // 表单校验
      rules: {
        app_id: [
          { required: true, message: "应用不能为空", trigger: "blur" }
        ],
        type: [
          { required: true, message: "类型不能为空", trigger: "change" }
        ],
        field: [
          { required: true, message: "字段不能为空", trigger: "blur" }
        ],
        label: [
          { required: true, message: "标签不能为空", trigger: "blur" }
        ],
        required: [
          { required: true, message: "必填不能为空", trigger: "change" }
        ],
        sorts: [
          { required: true, message: "排序不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    const appId = this.$route.params && this.$route.params.appId;
    this.appId = appId;
    this.queryParams.app_id = appId;

    let params = {"@table":"dev_app", "id":appId};
      apiGet(params).then(response => {
        this.appInfo = response.data;
        this.review();
      });
      
    this.getList();
  },
  methods: {
    /** 查询单字段列表 */
    getList() {
      this.loading = true;
      let params = {'@pager': this.pager};
      params['dev_app_form'] = {...this.queryParams};
      apiGet(params).then(response => {
        this.formList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
      
      this.review();
    },
    review() {
      let p = document.getElementById('preview');
      if(p){
        p.contentWindow.location.reload();
      }
    },
    loadApps() {
      let params = {"@table":"dev_app", "type":"form", "@pager":{limit:1000}};
      apiGet(params).then(response => {
        this.appOptions = response.data.rows;
      });
    },
    loadForms() {
      let params = {"@table":"dev_app_form", "app_id":this.copyForm.app_id, "@pager":{limit:1000}};
      apiGet(params).then(response => {
        this.formOptions = response.data.rows;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        app_id: this.appId,
        type: null,
        field: null,
        label: null,
        required: null,
        ds: null,
        mode: null,
        defaults: null,
        sorts: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.pager.page = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加表单字段";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
        let data = {};
        data['dev_app_form'] = { id:id};
      apiGet(data).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改表单字段";
      });
    },  
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
        let data = {
          'dev_app_form': this.form,
           '@tags': ['dev_app_form']
         };
          if (this.form.id != null) {
            apiPut(data).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            apiPost(data).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },  
    /** 复制按钮操作 */
    handleCopy() {
        this.loadApps();
      this.copyForm = {app_id: null, form_ids: []};
      this.openCopy = true;
    },
    cancelCopy() {
      this.copyForm = {app_id: null, form_ids: []};
      this.openCopy = false;
    },
    submitCopy() {
        if(this.copyForm.form_ids.length == 0){
            this.$modal.msgError("至少要选择一个字段");
            return;
        }
        let data = {
          'dev_app_form': [],
           '@tags': ['dev_app_form']
         };
        this.copyForm.form_ids.forEach(id => {
            let f = null;
            for(var i=0;i<this.formOptions.length;i++){
                if(this.formOptions[i].id == id){
                    f = this.formOptions[i];
                    break;
                }
            }
            if(this.formList && this.formList > 0){
                for(var i=0;i<this.formList.length;i++){
                    if(this.formList[i].field == f.field){
                        f = null;
                        break;
                    }
                }
            }
            
            if(f != null){
                let ff = {...f};
                ff.id = null;
                ff.app_id = this.appId;
                data['dev_app_form'].push(ff);
            }
        });
        
        if(data['dev_app_form'].length == 0){
            this.$modal.msgError("至少要选择一个字段");
            return;
        }
        apiPost(data).then(response => {
            this.$modal.msgSuccess("复制成功");
            this.openCopy = false;
            this.getList();
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除选中的表单字段数据？').then(function() {
        let data = {};
        data['dev_app_form'] = { id:ids, "@exp":{id:"in"}};
        data['@tags'] = ['dev_app_form'];
        return apiDelete(data);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    }
  }
};
</script>
